﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using clf.weighing.entity;


namespace weighing
{
    public class PermissionDao : BaseDao<Permission>
    {
        private static PermissionDao? instance;
        public static PermissionDao Instance => instance ??= new PermissionDao();

        public override string GetTableName()
        {
            return TableName.sys_permission.ToString();
        }

        public int Insert(Permission permission)
        {
            string sql = SqlBuilder.GetInsertSql(permission, GetTableName());
            return Sqlite.Insert(sql);
        }

        public  int Update(Permission permission)
        {
            string sql = SqlBuilder.GetUpdateSql(permission, GetTableName());
            return Sqlite.Update(sql);
        }

        public List<Permission> AllList()
        {
            //需要分组         
            string order = $"{PermissionField.id} asc";
            string sql = SqlBuilder.GetSelectSql(GetTableName(), null, null, null, null, order);
            List<Permission> data = Sqlite.Select<Permission>(sql);
            return data;
        }

        /// <summary>
        /// 获取用户的权限
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public List<Permission> GetUserPermissions(long userId)
        {
            List<Permission> permissions = new List<Permission>();
            if (userId <= 0) return permissions;
            string sql = $@" SELECT DISTINCT p.* from sys_permission as p
                            LEFT JOIN sys_role_permission as rp on p.id =rp.permission_id
                            LEFT JOIN sys_user_role as ur on ur.role_id = rp.role_id
                            LEFT JOIN user as u on u.id = ur.user_id
                            where u.id = {userId};";
            permissions = Sqlite.Select<Permission>(sql);
            return permissions;
        }

        internal List<Permission> Select(string sql)
        {
           return Sqlite.Select<Permission>(sql);
        }
    }
}
